package com.czy.owner.ui.message;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.czy.otherlib.swipetoloadlayout.OnRefreshListener;
import com.czy.otherlib.swipetoloadlayout.SwipeToLoadLayout;
import com.czy.owner.R;
import com.czy.owner.adapter.BaseRecyclerAdapter;
import com.czy.owner.adapter.MessageContactsAdapter;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.callback.RecyclerHeadersDecoration;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.MessageContacts;
import com.czy.owner.global.Constants;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseFragment;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.disk.DiskLruCacheHelper;
import com.czy.owner.utils.pinyin.CharacterParser;
import com.czy.owner.widget.RecyclerSideBar;
import com.easemob.cases.MessageHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.easeui.domain.EaseUser;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;

/**
 * Created by King on 2016/5/20 0020.
 */
public class ContactsFragment extends BaseFragment implements OnRefreshListener {
    @BindView(R.id.nsv_message_contacts_tips)
    NestedScrollView nsvNoneTips;
    @BindView(R.id.ll_message_contacts_wrapper)
    LinearLayout llWrapper;

    @BindView(R.id.refresh_target)
    RecyclerView rvContactsMember;
    @BindView(R.id.swipeToLoadLayout)
    SwipeToLoadLayout swipeToLoadLayout;
    @BindView(R.id.tv_message_contacts_dialog)
    TextView tvContactsDialog;
    @BindView(R.id.rvs_message_contacts_sidebar)
    RecyclerSideBar rvsContactsSideBar;

    private CharacterParser characterParser;
    private MessageContactsComparator pinyinComparator;
    private MessageContactsAdapter mAdapter;
    private List<MessageContacts> mContactsList = new ArrayList<>();
    private RecyclerHeadersDecoration headersDecor = null;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_message_contacts;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        RxBus.getDefault().register(this);
    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if(!UserHelper.getInstance().isLogined()){
            return;
        }
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new MessageContactsComparator();

        rvsContactsSideBar.setOnTouchingLetterChangedListener(new RecyclerSideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                int position = mAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    rvContactsMember.scrollToPosition(position);
                }

            }
        });


        mAdapter = new MessageContactsAdapter(getContext(), mContactsList);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        rvContactsMember.setLayoutManager(layoutManager);
        rvContactsMember.setAdapter(mAdapter);
        if(headersDecor != null){
            rvContactsMember.removeItemDecoration(headersDecor);
        }
        headersDecor = new RecyclerHeadersDecoration(mAdapter);
        rvContactsMember.addItemDecoration(headersDecor);
        rvContactsMember.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));

        //   setTouchHelper();
        mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                headersDecor.invalidateHeaders();
            }
        });

        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<MessageContacts>() {
            @Override
            public void onItemClick(int position, MessageContacts o, View view) {
                Intent intent = new Intent(getContext(), ContactsPanelActivity.class);
                intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, o);
                startActivity(intent);
            }
        });


        rvsContactsSideBar.setMaxHeight(20);
        rvsContactsSideBar.setTextView(tvContactsDialog);
        checkTips();
        swipeToLoadLayout.setRefreshing(false);
        swipeToLoadLayout.setOnRefreshListener(this);
        swipeToLoadLayout.setLoadMoreEnabled(false);
        if (mContactsList.size() == 0) getData();
        setListMarginBottom();

    }

    public void getData() {
        if ((int) SharedPreferencesUtils.getParam(getActivity(), UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) != 0) {
            RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_ADDRESS_BOOK);
            params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(getContext()).getSession());
            params.addBodyParameter("storeId", SharedPreferencesUtils.getParam(getActivity(), UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    String data = PhoneUtils.checkResponseFlag(getActivity(), result);
                    if (data != null) {
                        DiskLruCacheHelper cacheHelper = null;
                        try {
                            cacheHelper = new DiskLruCacheHelper(getContext());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if (cacheHelper != null) {
                            cacheHelper.put(UserHelper.getInstance().getUserAccount() + "_contacts", data, 3600);
                        }
                        Gson gson = new Gson();
                        mContactsList = gson.fromJson(data, new TypeToken<List<MessageContacts>>() {
                        }.getType());
                        for (int i = 0; i < mContactsList.size(); i++) {
                            String pinyin = characterParser.getSelling(mContactsList.get(i).getEmployeesName());
                            String sortString = pinyin.substring(0, 1).toUpperCase();

                            if (sortString.matches("[A-Z]")) {
                                mContactsList.get(i).setSortLetters(sortString.toUpperCase());
                            } else {
                                mContactsList.get(i).setSortLetters("#");
                            }
                            if (!TextUtils.isEmpty(mContactsList.get(i).getImKey())) {
                                EaseUser easeUser = new EaseUser(mContactsList.get(i).getImKey());
                                easeUser.setNick(mContactsList.get(i).getEmployeesName());
                                easeUser.setAvatar(mContactsList.get(i).getUserLogo());
                                easeUser.setEmployeeId("" + mContactsList.get(i).getStoreEmployeesId());
                                easeUser.setPhone(mContactsList.get(i).getContact());
                                MessageHelper.getInstance().saveContact(easeUser);
                            }

                        }
                        Collections.sort(mContactsList, pinyinComparator);
                        mAdapter.setList(mContactsList);
                        rvsContactsSideBar.setSortLetter(mAdapter.getArraySortLetters());
                        checkTips();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    swipeToLoadLayout.setRefreshing(false);
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    swipeToLoadLayout.setRefreshing(false);
                }
            });
        }

    }

    /* 调整RecyclerView与底部的距离,防页面内容被TAB遮挡 */
    private void setListMarginBottom() {
        /*Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.main_tab_bottom_bg);
        int width = mBitmap.getWidth();
        int height = mBitmap.getHeight();
        LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
        layoutParam.bottomMargin = height;
        llWrapper.setLayoutParams(layoutParam)*/
    }

    private void checkTips() {
        if (mAdapter.getItemCount() > 0) {
            nsvNoneTips.setVisibility(View.GONE);
        } else {
            nsvNoneTips.setVisibility(View.VISIBLE);
        }
    }

    public class MessageContactsComparator implements Comparator<MessageContacts> {

        public int compare(MessageContacts o1, MessageContacts o2) {
            if (o1.getSortLetters().equals("@")

                    || o2.getSortLetters().equals("#")) {
                return -1;
            } else if (o1.getSortLetters().equals("#")
                    || o2.getSortLetters().equals("@")) {
                return 1;
            } else {
                return o1.getSortLetters().compareTo(o2.getSortLetters());
            }
        }

    }

    @Override
    public void onRefresh() {
        getData();
    }


    // TODO  切换门店
    @Subscribe(code = Constants.SELECT_STORE_ID, threadMode = ThreadMode.MAIN)
    public void onSelectStoreSuccess(CommonEvent event) {
        getData();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);
    }
}
